package com.ruoyi.project.data.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.BasicCarUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.data.domain.*;
import com.ruoyi.project.data.mapper.TbTransportDriverCarMapper;
import com.ruoyi.project.data.mapper.WeightCarEnterMapper;
import com.ruoyi.project.ledger.domain.TbTransportWaybillLeaveCheck;
import com.ruoyi.project.ledger.mapper.TbTransportWaybillLeaveCheckMapper;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.project.data.mapper.TbTransportWaybillMapper;
import com.ruoyi.project.data.service.ITbTransportWaybillService;

import static com.ruoyi.common.utils.BasicCarUtils.chineseNumber2Int;
import static com.ruoyi.common.utils.BasicCarUtils.isNumeric;

/**
 * 运单Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-24
 */
@Service
public class TbTransportWaybillServiceImpl implements ITbTransportWaybillService
{
    @Value("${weight.api}")
    private String weightApiUrl;
    @Autowired
    private TbTransportWaybillMapper tbTransportWaybillMapper;
    @Autowired
    private TbTransportWaybillLeaveCheckMapper tbTransportWaybillLeaveCheckMapper;
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private TbTransportDriverCarServiceImpl tbTransportDriverCarServiceImpl;
    @Autowired
    private TbTransportDriverCarMapper tbTransportDriverCarMapper;
    @Autowired
    private WeightCarEnterMapper weightCarEnterMapper;

    /**
     * 查询运单
     *
     * @param waybillId 运单ID
     * @return 运单
     */
    @Override
    public Waybill selectTbTransportWaybillById(Long waybillId)
    {
        Waybill waybill = tbTransportWaybillMapper.selectTbTransportWaybillById(waybillId);
        if(waybill != null){
            if(waybill.getAbnormalDesc() == null || "".equals(waybill.getAbnormalDesc())){
                waybill.setAbnormalDesc("无");
            }
            String waybillNum = waybill.getWaybillNum();
            // 根据运单号获取出厂图片
            List<String> leaveImage = tbTransportWaybillMapper.selectLeaveImage(waybillNum);
            waybill.setLeaveImage(leaveImage);
            Double totalWeight = 0d;
            // 根据运单号获取收货人信息
            List<ReceiveUser> receiveUserList = tbTransportWaybillMapper.selectReceiveUserByWaybillNum(waybillNum);
            if(receiveUserList != null && receiveUserList.size() > 0){
                waybill.setReceiveUser(receiveUserList);
                for(ReceiveUser receiveUser : receiveUserList){
                    if(receiveUser.getGoodsWeight() != null && !"".equals(receiveUser.getGoodsWeight())){
                        totalWeight += Double.parseDouble(receiveUser.getGoodsWeight());
                    }
                }
            }
            waybill.setTotalWeight(String.valueOf(totalWeight));
            waybill.setReceiveNum(receiveUserList.size());
            // 根据运单号获取驾驶员信息
            Driver driver = tbTransportWaybillMapper.selectDriverByWaybillNum(waybillNum);
            if(driver != null){
                waybill.setDeiver(judgeAxisNumber(driver));
            }
            // 根据运单号获取称重信息
            List<WeightInformation> weightInformationList = tbTransportWaybillMapper.selectWeightByWaybillNum(waybillNum);
            if(weightInformationList != null && weightInformationList.size() > 0){
                int axle = 0;
                for(WeightInformation weight : weightInformationList){
                    if(weight.getbPlatePhoto() != null && !"".equals(weight.getbPlatePhoto())){
                        if (!weight.getbPlatePhoto().contains("ycsjoss.oss-cn-hangzhou.aliyuncs.com")){
                            weight.setbPlatePhoto(weightApiUrl+weight.getbPlatePhoto());
                        }
                    }else{
                        WeightRecord record = new WeightRecord();
                        record.setPlantNo(weight.getPlantNo());
                        record.setPlantColor(weight.getPlantColor());
                        record.setStationCode(weight.getStationCode());
                        record.setWeightTime(weight.getWeightTime());
                        // 从进出场获取图片
                        WeightCarEnter carEnter = weightCarEnterMapper.selectCarEnterByWeight(record);

                        if(carEnter != null && StringUtils.isNotEmpty(carEnter.getFrontPlatePhoto())){
                            weight.setbPlatePhoto(carEnter.getFrontPlatePhoto());
                        }
                    }
                    if(weight.getaPlatePhoto() != null && !"".equals(weight.getaPlatePhoto())){
                        if (!weight.getaPlatePhoto().contains("ycsjoss.oss-cn-hangzhou.aliyuncs.com")){
                            weight.setaPlatePhoto(weightApiUrl+weight.getaPlatePhoto());
                        }
                    }
//                    Map<String, Object> carAxleNum = tbTransportDriverCarMapper.getCarAxleNum(waybillNum);
//                    if (carAxleNum != null && StringUtils.isNotBlank(carAxleNum.get("carAxleNums").toString())){
//                        axle = axle + Integer.parseInt(carAxleNum.get("carAxleNums").toString());
//                    }
//                    if (carAxleNum != null && StringUtils.isNotBlank(carAxleNum.get("carAxleNumsG").toString())){
//                        axle = axle + Integer.parseInt(carAxleNum.get("carAxleNumsG").toString());
//                    }
//                    if (axle >6){
//                        axle =6;
//                    }
//                    if (weight.getIsCxyc().equals("1")){
//                        Double maxLimitWeight = tbTransportDriverCarMapper.getMaxLimitWeight(String.valueOf(axle));
//                        weight.setCzDesc(axle+"轴超"+maxLimitWeight.intValue()+"吨");
//                    }
                }
                waybill.setWeightList(weightInformationList);
            }
            if(driver != null){
                String stationCode = waybill.getStationCode();
                String plantNo = driver.getCarLicenceNumber();
                Map<String, Object> map = new HashMap<>();
                map.put("stationCode", stationCode);
                map.put("plantNo", plantNo);
                map.put("initiationTime", waybill.getInitiationTime());
                map.put("type","1");
                WeightCarEnter carEnter = weightCarEnterMapper.selectCarEnterByCarNo(map);
                waybill.setCarEnter(carEnter);
                map = new HashMap<>();
                map.put("stationCode", stationCode);
                map.put("plantNo", plantNo);
                map.put("initiationTime", waybill.getInitiationTime());
                map.put("type","2");
                WeightCarEnter carLeave = weightCarEnterMapper.selectCarEnterByCarNo(map);
                waybill.setCarLeave(carLeave);
            }
            // 判断运单异常信息
            StringBuffer sb = new StringBuffer();
            // 1、判断是否超重异常
            int czCount = tbTransportWaybillMapper.selectCzycCountByWaybillNum(waybillNum);
            if(czCount > 0){
                sb.append("超重异常").append(",");
            }
            // 2、判断是否无称重记录
            if(weightInformationList == null || weightInformationList.size() == 0 ){
                sb.append("无称重记录").append(",");
            }
            if(sb.length() > 0){
                waybill.setAbnormalDesc(sb.substring(0,sb.length() - 1));
            }

            if("1".equals(waybill.getIsLeaveCheck())){
                // 根据运单号获取车辆出场检查
                TbTransportWaybillLeaveCheck leaveCheck = tbTransportWaybillLeaveCheckMapper.selectTbTransportWaybillLeaveCheckByWaybillNum(waybillNum);
                waybill.setLeaveCheck(leaveCheck);
            }
        }
        return waybill;
    }

    /**
     * 查询运单列表
     *
     * @param tbTransportWaybill 运单
     * @return 运单
     */
    @Override
    public List<TbTransportWaybill> selectTbTransportWaybillList(TbTransportWaybill tbTransportWaybill)
    {
        List<TbTransportWaybill> list = tbTransportWaybillMapper.selectTbTransportWaybillList(tbTransportWaybill);
        if(list != null && list.size() > 0){
            for(TbTransportWaybill waybill : list){
                if(waybill.getAbnormalDesc() == null || "".equals(waybill.getAbnormalDesc())){
                    waybill.setAbnormalDesc("无");
                }
                Double totalWeight = 0d;
                // 根据运单号获取收货人信息
                List<ReceiveUser> receiveUserList = tbTransportWaybillMapper.selectReceiveUserByWaybillNum(waybill.getWaybillNum());
                if(receiveUserList != null && receiveUserList.size() > 0){
                    for(ReceiveUser receiveUser : receiveUserList){
                        if(receiveUser.getGoodsWeight() != null && !"".equals(receiveUser.getGoodsWeight())){
                            totalWeight += Double.parseDouble(receiveUser.getGoodsWeight());
                        }
                    }
                }
                waybill.setTotalWeight(String.valueOf(totalWeight));
            }
        }
        return list;
    }

    @Override
    public int deleteWeightByWaybill(Long id) {
        return tbTransportWaybillMapper.deleteWeightByWaybill(id);
    }

    @Override
    public List<Map<String, Object>> selectWaybillExport(Long[] ids) {
        List<Map<String, Object>> list = tbTransportWaybillMapper.selectWaybillExport(ids);
        if(list != null && list.size() > 0){
            List<SysDictData> carColorList = dictDataMapper.selectDictDataByType("car_color");
            for(Map<String, Object> map : list){
                if(map.get("waybillAxleNums") != null && !"".equals(map.get("waybillAxleNums"))){
                    // 根据车轴获取限重
                    String limitWeight = tbTransportWaybillMapper.selectLimitWeight(map.get("waybillAxleNums").toString());
                    map.put("limitWeight", limitWeight);
                }else{
                    map.put("limitWeight", "");
                }

                // 根据运单号获取收货人信息
                List<ReceiveUser> receiveUserList = tbTransportWaybillMapper.selectReceiveUserByWaybillNum(map.get("waybillNum").toString());
                if(receiveUserList != null && receiveUserList.size() > 0){
                    map.put("recipientGoods", receiveUserList.get(0).getRecipientGoods());
                    map.put("receiveCompany", receiveUserList.get(0).getCompany());
                    map.put("receiveAddress", receiveUserList.get(0).getAddress());

                }
                if(map.get("totalWeight") != null){
                    double totalWeight = Double.parseDouble(map.get("totalWeight").toString()) ;
                    map.put("totalWeight", totalWeight/1000);
                }else{
                    map.put("totalWeight","");
                }
                if(map.get("carColor") != null && !"".equals(map.get("carColor"))){
                    if(carColorList != null && carColorList.size() > 0){
                        for(SysDictData dict : carColorList){
                            if(map.get("carColor").equals(dict.getDictValue())){
                                map.put("carColor","("+dict.getDictLabel()+")");
                                break;
                            }
                        }
                    }
                }
                if(map.get("carColorG") != null && !"".equals(map.get("carColorG"))){
                    if(carColorList != null && carColorList.size() > 0){
                        for(SysDictData dict : carColorList){
                            if(map.get("carColorG").equals(dict.getDictValue())){
                                map.put("carColorG","("+dict.getDictLabel()+")");
                                break;
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 轴数判断
     * @param driver
     * @return
     */
    private Driver judgeAxisNumber(Driver driver){
        // 车轴判断
        if (StringUtils.isNotBlank(driver.getAxleNums()) && StringUtils.isNotBlank(driver.getDriverIdCard()) && StringUtils.isNotBlank(driver.getCarLicenceNumber())){
            // 根据身份证和车牌查询车型
            String carModel = tbTransportDriverCarServiceImpl.getModel(driver.getDriverIdCard(), driver.getCarLicenceNumber());
            String num = "";
            if (StringUtils.isNotBlank(carModel)){
                String model = BasicCarUtils.getRealModel(carModel);
                Car car = tbTransportDriverCarServiceImpl.getCar(model);
                if (car == null){
                    car = BasicCarUtils.getBasicCar(model);
                    if (car != null){
                        tbTransportDriverCarServiceImpl.insertCar(car);
                    }
                }
                if (car != null){
                    if (isNumeric(car.getAxleNumber())) {
                        num = car.getAxleNumber();
                    } else {
                        if (car.getAxleNumber().contains("线")){
                            String substring = car.getAxleNumber().substring(car.getAxleNumber().indexOf("线") - 1, car.getAxleNumber().indexOf("线"));
                            if (isNumeric(substring)) {
                                num = substring;
                            } else {
                                num = String.valueOf(chineseNumber2Int(substring));
                            }
                        }else {
                            String substring = car.getAxleNumber().substring(car.getAxleNumber().indexOf("轴") - 1, car.getAxleNumber().indexOf("轴"));
                            if (isNumeric(substring)) {
                                num = substring;
                            } else {
                                num = String.valueOf(chineseNumber2Int(substring));
                            }
                        }
                    }
                    car.setAxleNumber(num);
                    String allModel = carModel.split(model)[0] + car.getModel();
                    car.setModel(allModel);
                    driver.setCar(car);
                    if (num.equals(driver.getAxleNums())){
                        driver.setIsAxleNumsConform("0");
                    }else {
                        driver.setIsAxleNumsConform("1");
                    }
                }else {
                    driver.setIsAxleNumsConform("3");
                }

            }else {
                driver.setIsAxleNumsConformG("3");
            }
        }

        // 挂车车轴判断
        if (StringUtils.isNotBlank(driver.getAxleNumsG()) && StringUtils.isNotBlank(driver.getDriverIdCard()) && StringUtils.isNotBlank(driver.getCarLicenceNumberG())){
            // 根据身份证和车牌查询车型
            String carModel = tbTransportDriverCarServiceImpl.getModel(driver.getDriverIdCard(), driver.getCarLicenceNumberG());
            String num = "";
            if (StringUtils.isNotBlank(carModel)){
                String model = BasicCarUtils.getRealModel(carModel);
                Car car = tbTransportDriverCarServiceImpl.getCar(model);
                if (car == null){
                    car = BasicCarUtils.getBasicCar(model);
                    if (car != null){
                        tbTransportDriverCarServiceImpl.insertCar(car);
                    }
                }
                if (car != null){
                    if (isNumeric(car.getAxleNumber())) {
                        num = car.getAxleNumber();
                    } else {
                        if (car.getAxleNumber().contains("线")){
                            String substring = car.getAxleNumber().substring(car.getAxleNumber().indexOf("线") - 1, car.getAxleNumber().indexOf("线"));
                            if (isNumeric(substring)) {
                                num = substring;
                            } else {
                                num = String.valueOf(chineseNumber2Int(substring));
                            }
                        }else {
                            String substring = car.getAxleNumber().substring(car.getAxleNumber().indexOf("轴") - 1, car.getAxleNumber().indexOf("轴"));
                            if (isNumeric(substring)) {
                                num = substring;
                            } else {
                                num = String.valueOf(chineseNumber2Int(substring));
                            }
                        }
                    }
                    car.setAxleNumber(num);
                    String allModel = carModel.split(model)[0] + car.getModel();
                    car.setModel(allModel);
                    driver.setCarG(car);
                    if (num.equals(driver.getAxleNumsG())){
                        driver.setIsAxleNumsConformG("0");
                    }else {
                        driver.setIsAxleNumsConformG("1");
                    }
                }else {
                    driver.setIsAxleNumsConformG("3");
                }

            }else {
                driver.setIsAxleNumsConformG("3");
            }
        }
        return driver;
    }

}
